import Vue from 'vue'
import Router from 'vue-router'
import http from '@/utils/request.js'

Vue.use(Router)

/* Layout */
import Layout from '@/layout'

/**
 * constantRoutes
 * a base page that does not have permission requirements
 * all roles can be accessed
 */
export const constantRoutes = [
  {
    path: '/login',
    component: () => import('@/views/login/index'),
    hidden: true
  },

  {
    path: '/404',
    component: () => import('@/views/404'),
    hidden: true
  },

  {
    path: '/',
    component: Layout,
    redirect: '/dashboard',
    children: [{
      path: 'dashboard',
      name: 'Dashboard',
      component: () => import('@/views/dashboard/index'),
      meta: { title: '展示板', icon: 'dashboard' }
    }]
  },
  // {
  //   path: '/demo',
  //   component: Layout,
  //   redirect: '/demo',
  //   children: [{
  //     path: '/demo/inner',
  //     name: 'Dashboard',
  //     component: () => import('@/views/dashboard/index'),
  //     meta: { title: '菜单', icon: 'dashboard' }
  //   }]
  // },
  /** 
  {
    path: '/system',
    component: Layout,
    redirect: '/system/user-manager',
    name: 'System',
    meta: { title: '系统管理', icon: 'el-icon-s-help' },
    children: [
      {
        path: 'user-manager',
        name: 'user',
        component: () => import('@/views/user/index'),
        meta: { title: '用户管理', icon: 'table', perms: ['sys:user:add'] }
      },
      {
        path: 'dept-manager',
        name: 'dept',
        component: () => import('@/views/department/index'),
        meta: { title: '部门管理', icon: 'tree' }
      }
    ]
  },
  */
]

  // 404 page must be placed at the end !!!
const notFound = { path: '*', redirect: '/404', hidden: true }

const createRouter = () => new Router({
  // mode: 'history', // require service support
  scrollBehavior: () => ({ y: 0 }),
  routes: constantRoutes
})

const router = createRouter()

router.beforeEach((to, from, next) => {
  next()
})
/** */
let flag = false
router.beforeEach(async (to, from, next) => {
  if(Vue.$cookies.get('token')) {
    if(to.path === '/login') {
      next('/dashboard')
    }else {
      if(!flag) {
        const r = await http.get('/menu')
        flag = true
        const ms = r.data.data
        // 当 children为null, 要删除掉
        deleteNullChildren(ms)
        // 服务器端返回组件是字符串，前端将字符串转换为 组件
        resolveComponent(ms)
        // constantRoutes 只是负责菜单的渲染
        ms.forEach(m => constantRoutes.push(m))

        // 往内存中路由表中添加数据, 这个代码是异步
        router.addRoutes(ms)
        
        next(to.path)  // sys/user
      }else {
        next()
      }
    }
  }else if(to.path === '/login'){  // 到登录页面直接放过
    next()
  }else {   // 没有登录的情况下并且cookie没有值，到登录页面
    next('/login')
  }
})


// 递归将所有的children为null的属性删除掉
function deleteNullChildren(ms) {
  if(ms && ms.length > 0) {
    ms.forEach(m => {
      if(!m.children) {
        delete m.children
      }else {
        deleteNullChildren(m.children)
      }
    })
  } 
}

// 将字符串转换为前端组件
function resolveComponent(ms) {
  if(ms && ms.length > 0) {
    ms.forEach(m => {
      if(m.component === 'Layout'){
        m.component = Layout
      }else {
        m.component = loadView(m.component)
      }
      if(m.children) {
        resolveComponent(m.children)
      }
    })
  }
}

// 将字符串解析成路由组件
const loadView  = (name) => {
  return (resolve) => require([`@/views/${name}/index`], resolve)
}

export function resetRouter() {
  const newRouter = createRouter()
  router.matcher = newRouter.matcher // reset router
}

export default router
